package cn.zwx.distributed.lock.example.controller;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.integration.redis.util.RedisLockRegistry;
import org.springframework.integration.zookeeper.lock.ZookeeperLockRegistry;
import org.springframework.messaging.MessagingException;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Lock;

@RestController
@RequestMapping("/distribute")
public class DistributeLockController {

    private Logger logger = LoggerFactory.getLogger(DistributeLockController.class);
    @Resource
    private RedisLockRegistry redisLockRegistry;
    @Resource
    private ZookeeperLockRegistry zookeeperLockRegistry;






    @RequestMapping("/redis/lock")
    public String testDistributeLockForRedis(){
        String redisLockKey = "distribute-redis-lock" ;
        Lock lock = redisLockRegistry.obtain(redisLockKey);
        try {
//            if (!lock.tryLock(100, TimeUnit.MILLISECONDS)){
            if (!lock.tryLock()){
                return "业务正在处理中,请稍后进行重试！";
            }
            // 第一个参数 是获取锁等待的时间
           logger.info("获取redisLock:{}锁成功",redisLockKey);
           // 模拟业务处理
           TimeUnit.SECONDS.sleep(1);
        }catch (InterruptedException e){
            return "获取分布式失败,请稍后进行重试！";
        }finally {
            logger.info("释放redisLock:{}",redisLockKey);
            try {
                lock.unlock();
            }catch (IllegalStateException e){
                logger.info("释放redisLock:{}异常",redisLockKey,e);
            }
        }
        return "业务处理完成！！";
    }


    @RequestMapping("/zk/lock")
    public String testDistributeLockForZk(){
        String redisLockKey = "distribute-zk-lock" ;
        Lock lock = zookeeperLockRegistry.obtain(redisLockKey);
        try {
//            if (!lock.tryLock(100, TimeUnit.MILLISECONDS)){
            if (!lock.tryLock()){
                return "业务正在处理中,请稍后进行重试！";
            }
            // 第一个参数 是获取锁等待的时间
            logger.info("获取zkLock:{}锁成功",redisLockKey);
            // 模拟业务处理
            TimeUnit.SECONDS.sleep(1);
        }catch (InterruptedException e){
            return "获取分布式失败,请稍后进行重试！";
        }finally {
            logger.info("释放zkLock:{}",redisLockKey);
            try {
                lock.unlock();
            }catch (MessagingException e){
                logger.info("释放zkLock:{}异常",redisLockKey,e);
            }
        }
        return "业务处理完成！！";
    }
}
